package pdfsetter.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

import org.ghost4j.document.PDFDocument;
import org.ghost4j.renderer.SimpleRenderer;

import pdfsetter.core.schema.PageSelection;

@SuppressWarnings("serial")
public class PDFListPane extends JScrollPane {
	private List<PDFElement> files = new ArrayList<PDFElement>();
	private List<File> sourceFiles = new ArrayList<File>();
	
	private Box box = Box.createVerticalBox();
	private PageSelection pageSelection = null;
	
	public PDFListPane(JPanel view) {
		super(view);
		view.add(box);
		view.setBackground(Color.LIGHT_GRAY);
		view.setLayout(new BoxLayout(view, BoxLayout.PAGE_AXIS));
		setVerticalScrollBar(new JScrollBar());
		setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

		Dimension d = new Dimension(300, 800);
		setMinimumSize(d);
		setMaximumSize(d);
		setPreferredSize(d);
	}

	public void addPDF(File file) throws FileNotFoundException, IOException {
		sourceFiles.add(file);
		PDFDocument pdf = new PDFDocument();
		pdf.load(file);
		SimpleRenderer renderer = new SimpleRenderer();
		renderer.setResolution(30);
		List<Image> images = null;
		try {
			images = renderer.render(pdf);
		} catch (Exception e1) {}
		
		final PDFImageComponent n = new PDFImageComponent(images, new Dimension(252, 356));
		final int fileNo = files.size();
		PDFElement element = new PDFElement(pdf, 0, images, file.getName());
		final PDFElementPanel ne = new PDFElementPanel(n, element);
		n.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				pageSelection = new PageSelection(fileNo, files.get(fileNo).pageNo);
				for(Component c : box.getComponents())
					((PDFElementPanel) c).setBorder(null);
				ne.setBorder(BorderFactory.createLineBorder(Color.red));
			}
		});
		files.add(element);
		box.add(ne);
	}

	public void changePage(int pdfNo, int pageNo) {
		files.get(pdfNo).pageNo = pageNo;
	}
	
	public PageSelection getPageSelection() {
		return pageSelection;
	}
	
	public String getPageSelectionDesc() {
		return files.get(pageSelection.getFileNumber()).name + " / strona "
				+ (files.get(pageSelection.getFileNumber()).pageNo+1);
	}
	
	public List<File> getSourceFiles() {
		return sourceFiles;
	}

}
